var QueryForm; // 查询表单
var QueryWindow; // 查询窗口
var DeleteWindow;
var LogGridPanel, ZCDeleteGridPanel;
var LogStore, ZCDeleteStore; // 存放查询数据的表格的存贮变量
var selections, removeDelete; // 得到复选框选中的全部记录

/*
 * 通过查询条件连接数据库得到数据 --- 未完成
 * 
 */
var Query = function() {
	LogStore.baseParams['start'] = '0';
	LogStore.baseParams['limit'] = '20';
	LogStore.baseParams['assetName'] = QueryForm.form.findField('assetName').getValue();

	QueryWindow.hide();
	LogStore.reload();
}
var autoQuery = function() {
	LogStore.baseParams['start'] = '0';
	LogStore.baseParams['limit'] = '20';
	LogStore.baseParams['assetName'] = '';
	LogStore.reload();
}

var DeleteZC = function() {
	var deleteLog = ",";
	for (var i = 0; i < ZCDeleteStore.getCount(); i++) {
		var record = ZCDeleteStore.getAt(i);
		deleteLog = deleteLog + record.get('logID') + ",";
	}
//	alert(deleteLog);
	DeleteWindow.hide();
	Ext.Ajax.request({
				url : '/Shrek/deleteLogServlet',
				success : function(response, opts) {
					var result = Ext.util.JSON.decode(response.responseText);
					if (result.success) {
//						Ext.Msg.alert('succeed', result.msg, function() {
//									LogStore.reload();
//								}, null);
						alert(result.msg);
						LogStore.reload();
					}
				},
				failure : function() {
					Ext.Msg.ERROR('failed');
				},
				params : {
					operaterID : deleteLog
				}
			});
}
var AccessDBtoDelete = function() {
	var length = removeDelete.length;

	for (var i = 0; i < length; i++) {
		var record = removeDelete[0];
		ZCDeleteStore.remove(record);
	}
}
var DeleteSelectedLog = function() {
	BuildDeleteZCGrid();
	BuildDeleteWindow();

	var length = selections.length;

	for (var i = 0; i < length; i++) {
		var record = selections[i];
		ZCDeleteStore.add(record);
	}

	DeleteWindow.show();
}

/*
 * 建立存放资产信息的布局
 */
var BuildLogGrid = function() {
	var SelectModel = new Ext.grid.CheckboxSelectionModel({
				listeners : {
					selectionchange : function(sm) {
						selections = LogGridPanel.getSelectionModel()
								.getSelections();

						if (sm.getCount()) {
							LogGridPanel.removeButton.enable();
						} else {
							LogGridPanel.removeButton.disable();
						}
					}
				}
			});

	var LogColumnModel = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(),
			SelectModel,{
				header : 'LogID',
				sortable : true,
				dataIndex : 'logID'
			}, {
				header : 'ProductID',
				sortable : true,
				dataIndex : 'targetObject'
			}, {
				header : 'StartDate',
				sortable : true,
				dataIndex : 'startDate'
			}, {
				header : 'EndDate',
				sortable : true,
				dataIndex : 'endDate'
			},{
				header : 'BelongTo',
				sortable : true,
				dataIndex : 'belongTo'
			}]);
	var LogRecord = new Ext.data.Record.create([{
				name : 'logID'
			}, {
				name : 'targetObject'
			}, {
				name : 'startDate'
			}, {
				name : 'endDate'
			},{
				name : 'belongTo'
			}]);

	LogStore = new Ext.data.Store({
				proxy : new Ext.data.HttpProxy({
							url : '/Shrek/selectLogServlet'
						}),
				reader : new Ext.data.JsonReader({
							totalProperty : 'total',
							root : 'result'
						}, LogRecord)

			});

	LogGridPanel = new Ext.grid.GridPanel({
//				title : "If you make a criteria query, only the recent 5 records will be shown.",
				width : '100%',
				height : 500,
				layout : 'fit',
				store : LogStore,
				cm : LogColumnModel,
				sm : SelectModel,
				stripeRows : true,
				loadMask : true,
				viewConfig : {
					forceFit : true
				},
				plugins : new Ext.ux.PanelResizer({
							minHeight : 100
						}),
				tbar : [{
							iconCls : 'delete',
							id : 'delete',
							tooltip : 'delete record(s)',
							text : 'Delete',
							ref : '../removeButton',
							disabled : true,
							handler : DeleteSelectedLog
						}, '-', {
							iconCls : 'query',
							text : 'Query',
							tooltip : 'do the query',
							handler : function() {
								QueryWindow.show();
							}
						}],
				bbar : new Ext.PagingToolbar({
							pageSize : 20,
							store : LogStore,
							displayInfo : true,
							plugins : new Ext.ux.ProgressBarPager()
						})
			});

}

var BuildDeleteZCGrid = function() {
	var SelectModel = new Ext.grid.CheckboxSelectionModel({
				listeners : {
					selectionchange : function(sm) {
						removeDelete = ZCDeleteGridPanel.getSelectionModel()
								.getSelections();

						if (sm.getCount()) {
							ZCDeleteGridPanel.removeButton.enable();
						} else {
							ZCDeleteGridPanel.removeButton.disable();
						}
					}
				}
			});

	var LogColumnModel = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), SelectModel,
	        {
				header : 'logID',
				sortable : true,
				dataIndex : 'logID'
	        }, {
				header : 'assetNo',
				sortable : true,
				dataIndex : 'targetObject'
			}, {
				header : 'startDate',
				sortable : true,
				dataIndex : 'startDate'
			}, {
				header : 'endDate',
				sortable : true,
				dataIndex : 'endDate'
			},{
				header : 'belongTo',
				sortable : true,
				dataIndex : 'belongTo'
			}/*, {
				header : 'ID',
				sortable : true,
				dataIndex : 'id'
			}, {
				header : '日期',
				sortable : true,
				dataIndex : 'operateDate'
			}, {
				header : '描述',
				sortable : true,
				dataIndex : 'description'
			}, {
				header : '操作状态',
				sortable : true,
				dataIndex : 'operateStatus'
			}*/]);

	var LogRecord = new Ext.data.Record.create([{
				name : 'logID'
			}, {
				name : 'targetObject'
			}, {
				name : 'startDate'
			}, {
				name : 'endDate'
			}, {
				name : 'belongTo'
			}/*, {
				name : 'targetObject'
			}, {
				name : 'operateDate'
			}, {
				name : 'description'
			}, {
				name : 'operateStatus'
			}*/]);

	ZCDeleteStore = new Ext.data.Store({
				proxy : new Ext.data.MemoryProxy(),
				reader : new Ext.data.ArrayReader({}, LogRecord)
			});

	ZCDeleteGridPanel = new Ext.grid.GridPanel({
				width : '100%',
				autoHeight : true,
				store : ZCDeleteStore,
				cm : LogColumnModel,
				sm : SelectModel,
				stripeRows : true,
				loadMask : true,
				tbar : ['->', {
							iconCls : 'delete',
							id : 'delete',
							tooltip : 'remove the records you have choosed to delete',
							text : 'Remove',
							ref : '../removeButton',
							disabled : true,
							handler : AccessDBtoDelete
						}]
			});
};

/*
 * 建立查询日志信息的布局
 */
var BuildQueryForm = function() {
	QueryForm = new Ext.form.FormPanel({
				labelAlign : 'right',
				labelWidth : 70,
				width : '100%',
				bodyStyle : 'padding:20px 10px;',
				items : [{
							layout : 'column',
							border : false,
							items : [{
										bodyStyle : 'padding-top:5px',
										columnWidth : .9,
										layout : 'form',
										defaults : {
											width : 130
										},
										defaultType : 'textfield',
										items : [{
													fieldLabel : 'ProductID',
													name : 'assetName'
												}/*, {
													fieldLabel : '操作对象',
													name : 'targetObject',
													xtype : 'combo',
													store : [],
													emptyText : '请选择',
													mode : 'local',
													triggerAction : 'all',
													valueField : 'text',
													displayField : 'text'
												}*/]
									}/*, {
										bodyStyle : 'padding-top:5px',
										columnWidth : .5,
										style : 'margin-left: 15px;',
										layout : 'form',
										defaults : {
											width : 130
										},
										defaultType : 'textfield',
										items : [{
													fieldLabel : '开始日期',
													name : 'StartUseTime',
													xtype : 'datefield',
													emptyText : '请选择',
													format : 'Y-m-d',
													readOnly : true
												}, {
													fieldLabel : '结束日期',
													name : 'EndUseTime',
													xtype : 'datefield',
													emptyText : '请选择',
													format : 'Y-m-d',
													readOnly : true
												}]
									}*/]
						}]
			})
}

/*
 * 建立查询资产信息的窗口 --- 存放QueryForm
 */
var BuildQueryWindow = function() {
	QueryWindow = new Ext.Window({
				title : '~ Query Window ~',
				width : 300,
				heigth : 400,
				modal : true,
				resizable : false,
				closeAction : 'hide',
				items : [QueryForm],
				buttons : [{
							iconCls : 'query',
							text : 'Query',
							handler : Query
						}, {
							iconCls : 'empty',
							text : 'Empty',
							handler : function() {
								QueryForm.getForm().reset();
							}
						}],
				buttonAlign : 'center'
			})
}

var BuildDeleteWindow = function() {
	DeleteWindow = new Ext.Window({
				title : '~ Delete Window~',
				modal : true,
				width : 570,
				heigth : 300,
				closeAction : 'hide',
				resizable : true,
				items : [ZCDeleteGridPanel],
				buttons : [{
							iconCls : 'ok',
							text : 'Save',
							handler : DeleteZC
						}, {
							iconCls : 'cancel',
							text : 'Return',
							handler : function() {
								DeleteWindow.hide();
							}
						}],
				buttonAlign : 'center'
			})
}
var BuildLayout = function() {
	new Ext.Viewport({
				layout : 'border',
				items : [{
							region : 'center',
							layout : 'fit',
							items : [LogGridPanel]
						}]
			})
};

/*
 * 初始化各个界面的布局
 */
var init = function() {
	Ext.QuickTips.init();
	Ext.form.Field.prototype.msgTarget = 'side';
	BuildLogGrid();
	BuildQueryForm();
	BuildQueryWindow();
	BuildLayout();
	if(namese == 'guest')
    {
		LogGridPanel.getTopToolbar().items.get('delete').hide();
    }
	autoQuery();
}

Ext.onReady(init);